#    This file is part of OpenPolitik.
#
#    OpenPolitik is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    OpenPolitik is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with OpenPolitik.  If not, see <http://www.gnu.org/licenses/>.
import os

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template

import op_models

def get_path(page):
	return os.path.join(os.path.dirname(__file__) + "/templates/", page + ".html")

def get_liu_stuff(redirect_uri):
	user = users.get_current_user()

	ret = {}
	if user:
		url = users.create_logout_url("/")
		url_linktext = "Logout"

		uigs = op_models.UserInGame.all().filter("user = ", user).fetch(10)

		ret["games"] = [u.game for u in uigs]
	else:
		url = users.create_login_url(redirect_uri)
		url_linktext = "Login"

	ret.update({	
		"liu": user,
		"login_url": url,
		"login_url_linktext": url_linktext,
	})
	return ret

def load_territories():
	f = open("nations.dat", "r")
	lines = f.readlines()
	f.close()

	obj = None
	objs = {}

	for line in lines:
		if line[0] == "#":
			# comment, do nothing
			pass
		elif line[0] == "\t":
			# object parameter
			line = line.strip().split(":")
			lhs = line[0].strip()
			rhs = line[1].strip()

			obj[lhs] = rhs
		else:
			if obj:
				objs[obj["name"]] = obj
				obj = None

			line = line.strip()
			obj = { "name": line }
	
	if obj:
		objs[obj["name"]] = obj
	
	return objs

def process_pieces(pieces):
	nations = load_territories()

	pieces = [p.split(" ", 2) for p in pieces.split("\n") if p != ""]

	errors = []
	result = []
	for p in pieces:
		if len(p) != 3:
			errors.append("Line '%s' does not make sense." % " ".join(p))
			continue

		owner = p[0].upper()
		type = p[1].upper()
		loc = p[2].lower().strip()

		nation = nations[loc]

		if nation == None:
			errors.append("Nation %s does not exist." % loc)
			continue

		x = y = 0
		if type == "SC":
			# check to see if the location can have an SC
			if nation["sc"] != "1":
				errors.append("Nation %s can't have a supply centre." % loc)
			else:
				x = nation["sc-x"]
				y = nation["sc-y"]
		else:
			x = nation["x"]
			y = nation["y"]

		piece = {
			"owner": op_models.NATIONS_SHORT.index(owner),
			"type": op_models.PIECES.index(type),
			"loc": loc,
			"x": int(x),
			"y": int(y)
		}
		result.append(piece)

	return result, errors
